/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Almacen;

import Controlador.Bean.Almacen.EntradaSalida;
import Controlador.Bean.Almacen.Producto;
import Controlador.Bean.Almacen.ProdxSolicitudMovimiento;
import Controlador.Bean.Almacen.SolicitudMovimiento;
import gui.General.Main;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import lib.Validaciones;

/**
 *
 * @author César
 */
public class DetalleAjuste extends javax.swing.JPanel {

    /**
     * Creates new form DetalleAjuste
     */
    
    String idAlmacen;
    TableModel tb;
    DetalleAjuste dt = this;
    public DetalleAjuste(String idAlmacen) {
        this.idAlmacen = idAlmacen;
        tb = new TableModel();
        List<Producto> productos = Controlador.Service.Almacen.GestionAlmacenes.filtrarProductosporAlmacen(idAlmacen, "", "");
        ArrayList<Ajuste> pajuste = new ArrayList<Ajuste>();
        for(int i=0; i<productos.size(); i++){
            pajuste.add(new Ajuste(productos.get(i), 0.0));
        }
        tb.data = pajuste;
        initComponents();
        initComp();
    }
    
    /**
     *
     */
    private void initComp(){
        //tblProducto.repaint();
        
        
    }
    
    class Ajuste{
        Producto p;
        Double cantidad;
        
        public Ajuste(){
            
        }
        
        public Ajuste(Producto p, Double cantidad){
            this.p = p;
            this.cantidad = cantidad;
        }
    }

    class TableModel extends AbstractTableModel{
        
        //Two arrays used for the table data
        String[] columnNames = {"Código", "Nombre", "Descripción"
                        , "Cantidad", "Unidad Métrica" , "Ajuste"};
               
        public List<Ajuste> data;
        
        
        public void actualizarTabla(){
            //data = Controlador.Service.Almacen.GestionAlmacenes.filtrarProductosporAlmacen(idAlmacen, "", "");
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount()
        {
            return data.size();
        }
        
        
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public void setValueAt(Object o, int row, int column){
            try{
                data.get(row).cantidad = Double.parseDouble((String) o);
                fireTableDataChanged();
            }catch(Exception e){
                JOptionPane.showMessageDialog(dt, "Ingrese un Real Positivo o Negativo", "Error", JOptionPane.ERROR_MESSAGE);
            }
                
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {   
            switch(column){
                case 0: return data.get(row).p.getIdProducto();
                case 1: return data.get(row).p.getNombre();
                case 2: return data.get(row).p.getDescripcion();
                case 3: return data.get(row).p.getCantidad();
                case 4: return data.get(row).p.getUnidadMedida();
                default: return data.get(row).cantidad;
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public boolean isCellEditable(int row, int column) {
            if(column == 5)
                return true;
            return false;
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
//        @Override
//        public Class getColumnClass(int c) {
//            if(c!=7){
//            return getValueAt(0, c).getClass();
//            }else{
//                return JButton.class;
//            }
//        }

        
     }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblProducto = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar Producto"));

        jLabel1.setText("Id");

        jLabel2.setText("Nombre");

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnBuscar))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(btnLimpiar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(97, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuscar)
                    .addComponent(btnLimpiar))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
        jPanel2.setLayout(new java.awt.BorderLayout());

        tblProducto.setModel(tb);
        jScrollPane2.setViewportView(tblProducto);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        btnCancelar.setText("Cancelar");

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        List<Producto> productos = Controlador.Service.Almacen.GestionAlmacenes.filtrarProductosporAlmacen(idAlmacen, txtId.getText(), txtNombre.getText());
        ArrayList<Ajuste> pajuste = new ArrayList<Ajuste>();
        for(int i=0; i<productos.size(); i++){
            pajuste.add(new Ajuste(productos.get(i), 0.0));
        }
        tb.data = pajuste;
        tb.actualizarTabla();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        // TODO add your handling code here:
        List<Producto> productos = Controlador.Service.Almacen.GestionAlmacenes.filtrarProductosporAlmacen(idAlmacen, "", "");
        ArrayList<Ajuste> pajuste = new ArrayList<Ajuste>();
        for(int i=0; i<productos.size(); i++){
            pajuste.add(new Ajuste(productos.get(i), 0.0));
        }
        tb.data = pajuste;
        tb.actualizarTabla();
        txtId.setText("");
        txtNombre.setText("");
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        SolicitudMovimiento LentradaSalida = new SolicitudMovimiento("id", Main.usu.getIdEmpleadoAdm(),idAlmacen, "Ajuste", new Date(), "Ajuste de Almacen", "1","Interno");
        Controlador.Service.Almacen.GestionAlmacenes.agregarSolicitudMovimiento(LentradaSalida);
        List<ProdxSolicitudMovimiento> pSolMov = new ArrayList<>();
        for(int i=0;i<tb.data.size(); i++){
            if(tb.data.get(i).cantidad!=0){
                pSolMov.add(new ProdxSolicitudMovimiento(tb.data.get(i).p.getIdProducto(), LentradaSalida.getIdSolicitudMovimiento(), tb.data.get(i).cantidad));                
                tb.data.get(i).cantidad = 0.0;
            }
        }
        Controlador.Service.Almacen.GestionAlmacenes.agregarProdxSolMov(pSolMov, idAlmacen, "Ajuste");
        tb.fireTableDataChanged();
        JOptionPane.showMessageDialog(this, "Ajuste realizado correctamente", "Confirmación", JOptionPane.INFORMATION_MESSAGE);
        
    }//GEN-LAST:event_btnGuardarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblProducto;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
